<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\CommentRequest;
use App\Models\Comment;
use App\Models\User;
use App\Transformers\CommentTransformer;
use Illuminate\Http\Request;

class CommentsController extends Controller
{
    public function show($id)
    {
        $data = Comment::find($id);

        if (!$data) {
            $this->response->error(trans('api.not_exists'), 200);
        }

        return $this->response->item($data, new CommentTransformer([], $this->user));
    }

    public function create(CommentRequest $request)
    {
        $data = $request->only([
            'object_id',
            'object_type',
            'content',
        ]);
        $data['object_type'] = 'App\Models\\' . ucfirst(strtolower($data['object_type']));
        $data['user_id'] = $this->user->id;
        $data['user_type'] = 'App\Models\User';

        //判断对象是否存在
        $object = new $data['object_type']();

        $check = $object->find($data['object_id']);

        if (!$check) {
            $this->response->error(trans('api.save_failed') . 'object' . trans('api.not_exists'), 200);
        }

        //判断用户是否禁言
        if ($this->user->gag_status == User::FORBIDDEN) {
            $this->response->error(trans('api.gag_forbidden'), 200);
        }

        $res = Comment::create($data);

        if ($res) {
            return response()->json(['message' => trans('api.save_succeed'), 'code' => 1, 'status' => true, 'data' => ''], 200);
        } else {
            return response()->json(['message' => trans('api.save_failed'), 'code' => 0, 'status' => false], 200);
        }
    }

}
